<template>
  <div class="page-wrapper form-designer-grid">
    <vxe-layout-container>
      <vxe-layout-body class="form-designer-view">
        <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
          <template #customTop>
            <vxe-notice-bar content="自定义底部区域" />
          </template>
        </vxe-grid>
      </vxe-layout-body>
      <vxe-layout-aside vertical class="form-designer-config">
        <el-tabs v-model="activeName" @tab-click="handleConfigClick">
          <el-tab-pane label="基础设置" name="basicConfig">
            <el-form :model="basicConfigModel" label-width="auto">
              <el-divider content-position="left" border-style="dashed">查询设置</el-divider>

              <!--              <el-form-item label="开启查询">-->
              <!--                <el-switch-->
              <!--                  v-model="formConfigQueryEnabled"-->
              <!--                  active-color="#13ce66"-->
              <!--                  inactive-color="#ff4949"-->
              <!--                />-->
              <!--              </el-form-item>-->

              <el-form-item label="查询条件" tooltip="折叠查询表单">
                <el-button type="text" @click="gridQueryConfig">条件设置</el-button>
              </el-form-item>

              <el-divider content-position="left" border-style="dashed">列配置</el-divider>
              <!--              <el-form-item label="显示序号">-->
              <!--                <el-switch-->
              <!--                  v-model="gridOptions.showIndex"-->
              <!--                  active-color="#13ce66"-->
              <!--                  inactive-color="#ff4949"-->
              <!--                />-->
              <!--              </el-form-item>-->

              <el-form-item label="展示列">
                <el-button type="text" @click="gridRef.openCustom()">列设置</el-button>
              </el-form-item>
              <el-form-item label="高亮当前列">
                <el-switch
                  v-model="columnConfigRef.isCurrent"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-divider content-position="left" border-style="dashed">工具栏配置</el-divider>
              <el-form-item label="操作功能">
                <el-checkbox-group v-model="basicConfigModel.buttons">
                  <el-checkbox
                    v-for="op in DataTableOperator"
                    :key="op.code"
                    :value="op.code"
                    :label="op.name"
                    type="name"
                  />
                </el-checkbox-group>
              </el-form-item>

              <el-divider content-position="left" border-style="dashed">显示设置</el-divider>
              <el-form-item label="是否展示表格线">
                <el-switch
                  v-model="gridOptions.border"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item label="是否展示表格斑马纹">
                <el-switch
                  v-model="gridOptions.stripe"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item label="是否展示表头">
                <el-switch
                  v-model="gridOptions.showHeader"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item label="是否展示表尾">
                <el-switch
                  v-model="gridOptions.showFooter"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item label="表格宽度">
                <el-input v-model="gridOptions.width" placeholder="请设置表格宽度" />
              </el-form-item>
              <el-form-item label="表格高度">
                <el-input v-model="gridOptions.height" placeholder="请设置表格高度" />
              </el-form-item>
              <el-form-item label="分页设置">
                <el-radio-group v-model="gridOptions.pagerConfig.enabled">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
                <el-select
                  placeholder="分页大小"
                  v-show="gridOptions.pagerConfig.enabled"
                  v-model="gridOptions.pagerConfig.pageSize"
                >
                  <el-option
                    v-for="item in pageSizeOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="空数据显示">
                <el-input v-model="gridOptions.emptyText" placeholder="请设置空数据显示文字" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="高级设置" name="advancedConfig">功能</el-tab-pane>
        </el-tabs>
      </vxe-layout-aside>
    </vxe-layout-container>
  </div>
</template>

<script lang="ts" setup>
import { VxeGridInstance, VxeGridListeners, VxeGridProps, VxeTableDefines } from 'vxe-table'
import { useApprovalDesignerStore } from '@/store/modules/dsgn/ApprovalDesigner'
import {
  DataTableOperator,
  DTColumns2FormCondition,
  DTOperator,
  DtOperatorConvertGird,
  FormCreateRule2Tbl,
  VxeQueryColumn
} from '@/api/res/FormDsgn/DataTable/DataTable'
import { TabsPaneContext } from 'element-plus'
import { getFormCreateRules } from '@/api/res/FormDsgn/DataTable/FormCreateConvert'

import VueDraggable from 'vuedraggable'
const gridRef = ref<VxeGridInstance>()

interface RowVO {
  id: number | string
}

const activeName = ref('basicConfig')

const handleConfigClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const pageSizeOptions = ref([
  { id: 10, label: '10条/页' },
  { id: 15, label: '15条/页' },
  { id: 20, label: '20条/页' },
  { id: 50, label: '50条/页' },
  { id: 100, label: '100条/页' }
])
// const basicConfigRules = ref({})
//
// const advancedConfigModel = ref({})

const operatorBtnsDragEnd = () => {
  // updateParentData()
  // console.log('新的顺序:', choosePattern.value)
}

const basicConfigModel = ref({
  buttons: [DataTableOperator.add.code],
  pageSize: 40
})
const girdOptsTooBarConfig = ref({
  zoom: {
    iconIn: 'vxe-icon-fullscreen',
    iconOut: 'vxe-icon-minimize'
  },
  custom: {
    status: 'primary',
    icon: 'vxe-icon-layout'
  },
  tools: [
    {
      title: '同步表单列表结构',
      code: 'columnRefresh',
      circle: true,
      icon: 'vxe-icon-repeat'
    },
    {
      title: '同步表单列表结构并刷新数据',
      code: 'columnAndDataRefresh',
      circle: true,
      icon: 'vxe-icon-refresh'
    }
  ],
  buttons: DtOperatorConvertGird(basicConfigModel.value.buttons) as DTOperator[]
})

const formConfigQueryCollapse = ref(true)

// const formConfigQueryEnabled = ref(true)

const formConfigRef = ref({
  data: {},
  items: []
})
/**
 * 查询条件配置
 */
const gridQueryConfig = () => {
  // formConfigQueryCollapse.value = !formConfigQueryCollapse.value

  const gridColumns = gridOptions.columns
  const newColumnsList: VxeQueryColumn[] = DTColumns2FormCondition(gridColumns)
  formConfigRef.value = {
    data: {},
    items: []
  }
  newColumnsList.forEach((item) => {
    formConfigRef.value.data[item.field] = ''
  })
  newColumnsList.push({
    span: 24,
    collapseNode: true,
    align: 'center',
    itemRender: {
      name: 'VxeButtonGroup',
      options: [
        { type: 'submit', content: '搜索', status: 'primary' },
        { type: 'reset', content: '重置' }
      ]
    }
  })
  formConfigRef.value.items = newColumnsList
}

// const gridCondition=computed(gridQueryConfig)

// formConfigRef.value.items.push(formConfigQuery.value)
const columnConfigRef = ref({
  drag: true,
  resizable: true,
  isCurrent: true,
  isHover: true
})

const gridOptions = reactive<VxeGridProps<RowVO>>({
  emptyText: '没有更多数据了！',
  border: true,
  stripe: true,
  showHeader: true,
  loading: false,
  formConfig: formConfigRef,
  width: '100%',
  height: '100%',
  // 自定义工具栏
  toolbarConfig: girdOptsTooBarConfig,
  pagerConfig: {
    enabled: true,
    pageSize: 15
  },
  proxyConfig: {
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      // 接收 Promise
      query: ({ page }) => {
        return fetchApi(page.currentPage, page.pageSize)
      }
    }
  },
  customConfig: {
    mode: 'drawer',
    // slots: {
    //   top: 'customTop'
    // },
    storage: true,
    restoreStore({ id }) {
      return findCustomSetting(id)
    },
    updateStore({ id, storeData }) {
      // 模拟异步，实现服务端保存
      return saveCustomSetting(id, storeData)
    }
  },
  columnConfig: columnConfigRef,
  rowConfig: {
    isHover: true
  },
  checkboxConfig: {
    labelField: 'id',
    highlight: true,
    range: true
  },
  columns: [],
  data: []
})
// 模拟后台接口
const fetchApi = (currentPage: number, pageSize: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const list = [
        {
          id: 10001,
          name: 'Test1',
          nickname: 'T1',
          role: 'Develop',
          sex: 'Man',
          age: 28,
          address: 'Shenzhen'
        },
        {
          id: 10002,
          name: 'Test2',
          nickname: 'T2',
          role: 'Test',
          sex: 'Women',
          age: 22,
          address: 'Guangzhou'
        }
      ]
      resolve({
        page: {
          total: list.length
        },
        result: list.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      })
    }, 100)
  })
}

const gridEvents: VxeGridListeners<RowVO> = {
  custom({ type }) {
    console.log(type)
  },
  formSubmit() {
    console.log('form submit')
  },
  formReset() {
    console.log('form reset')
  },
  toolbarButtonClick({ code }) {
    const $grid = gridRef.value
    if ($grid) {
      switch (code) {
        case DataTableOperator.add.code: {
          $grid.insert({
            name: 'xxx'
          })
          break
        }
        case DataTableOperator.batchDelete.code: {
          const selectRecords = $grid.getCheckboxRecords()
          $grid.remove(selectRecords)
          break
        }
        case DataTableOperator.save.code: {
          // const { insertRecords, removeRecords, updateRecords } = $grid.getRecordset()
          // VxeUI.modal.message({ content: `新增 ${insertRecords.length} 条，删除 ${removeRecords.length} 条，更新 ${updateRecords.length} 条`, status: 'success' })
          break
        }
        case DataTableOperator.export.code: {
          $grid.exportData({
            type: 'csv'
          })
          break
        }
      }
    }
  },
  toolbarToolClick({ code }) {
    const $grid = gridRef.value
    if ($grid) {
      switch (code) {
        case 'columnRefresh':
          loadColumConfig()
          break
        case 'columnAndDataRefresh':
          loadColumData()
          break
      }
    }
  }
}

/** 初始化 **/
onBeforeUpdate(() => {
  loadColumConfig()
})

const loadColumConfig = () => {
  const widgetRules = getFormCreateRules()
  gridOptions.columns = FormCreateRule2Tbl(widgetRules) as any
}

// 模拟查询接口
const findCustomSetting = (id: string) => {
  return new Promise<VxeTableDefines.CustomStoreData>((resolve) => {
    setTimeout(() => {
      try {
        if (sessionStorage.getItem(id)) {
          resolve(JSON.parse(sessionStorage.getItem(id) || '') as VxeTableDefines.CustomStoreData)
          // VxeUI.modal.message({
          //   status: 'success',
          //   content: '异步还原用户个性化数据成功'
          // })
        } else {
          resolve({})
        }
      } catch (e) {
        resolve({})
      }
    }, 500)
  })
}

// 模拟保存接口
const saveCustomSetting = (id: string, storeData: VxeTableDefines.CustomStoreData) => {
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      console.log(storeData)
      sessionStorage.setItem(id, JSON.stringify(storeData))
      // VxeUI.modal.message({
      //   status: 'success',
      //   content: '保存用户个性化数据成功'
      // })
      resolve()
    }, 200)
  })
}

const loadColumData = () => {
  // 模拟后台接口
  gridOptions.loading = true
  setTimeout(() => {
    loadColumConfig()
    gridOptions.data = [
      { id: 10001, name: 'Test1', role: 'Develop', sex: 'Man', age: 28, address: 'test abc' },
      { id: 10002, name: 'Test2', role: 'Test', sex: 'Women', age: 22, address: 'Guangzhou' },
      { id: 10003, name: 'Test3', role: 'PM', sex: 'Man', age: 32, address: 'Shanghai' },
      { id: 10004, name: 'Test4', role: 'Designer', sex: 'Women', age: 24, address: 'Shanghai' }
    ]
    gridOptions.loading = false
  }, 500)
}

// 监听 basicConfigModel.buttons 的变化
watch(
  () => basicConfigModel.value.buttons,
  (newVal, oldVal) => {
    girdOptsTooBarConfig.value.buttons = DtOperatorConvertGird(basicConfigModel.value.buttons)
  },
  { deep: true } // 如果 buttons 是一个对象或者数组，并且你需要监听其内部的变化，需要设置 deep: true
)

// watch(
//   () => formConfigQueryEnabled.value,
//   (newVal, oldVal) => {
//     if(newVal){
//       formConfigQuery.value={};
//     }else{
//       formConfigQuery.value={
//         span: 24,
//         collapseNode: formConfigQueryCollapse,
//         align: 'center',
//         itemRender: {
//           name: 'VxeButtonGroup',
//           options: [
//             { type: 'submit', content: '搜索', status: 'primary' },
//             { type: 'reset', content: '重置' }
//           ]
//         }
//       }
//     }
//   }
// )

// 监听 gridOptions.columns 的变化
watch(
  () => gridOptions.columns,
  (newVal, oldVal) => {
    // girdOptsTooBarConfig.value.buttons = DtOperatorConvertGird(basicConfigModel.value.buttons)
    console.log(newVal, oldVal)
  },
  { deep: true } // 如果 buttons 是一个对象或者数组，并且你需要监听其内部的变化，需要设置 deep: true
)
</script>

<style lang="scss" scoped>
.form-designer-grid {
  padding-top: 10px;
}

.form-designer-view {
  ::v-deep .vxe-tools--wrapper {
    margin-right: 10px;
  }
}

.form-designer-add-view {
  margin: 0 7px;
}

.form-designer-config {
  padding-left: 10px;
}

.form-designer-view {
  margin-right: 10px;
}

.form-designer-card {
  //margin: 10px;
  //border:none;
}
</style>
